package com.example.park_management.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.park_management.common.Result;
import com.example.park_management.domain.Assets;
import com.example.park_management.domain.Rooms;
import com.example.park_management.domain.vo.RoomVo;
import com.example.park_management.service.RoomsService;
import com.example.park_management.mapper.RoomsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

/**
* @author xiaoming
* @description 针对表【rooms(房间)】的数据库操作Service实现
* @createDate 2024-05-28 17:04:33
*/
@Service
public class RoomsServiceImpl extends ServiceImpl<RoomsMapper, Rooms>
    implements RoomsService{

    @Autowired
    private RoomsMapper roomsMapper;
    @Resource
    private AssetsServiceImpl assetsService;
    @Override
    public int createRoom(Rooms rooms) {
        roomsMapper.insert(rooms);
        return rooms.getRoomId();
    }
    @Override
    @Transactional // 添加事务管理
    public Result updateRoomWithOptionalOwner(RoomVo rooms) {
        // 更新房间信息的逻辑...

        // 删除原有资产关联
        assetsService.removeAllAssociationsByRoomId(rooms.getRoomId());

        // 处理ownerId
        if (rooms.getOwnerId() != null && !rooms.getOwnerId().trim().isEmpty()) {
            try {
                int ownerId = Integer.parseInt(rooms.getOwnerId());

                // 检查关联是否已存在
                if (!assetsService.isAssetAssociatedWithRoom(rooms.getRoomId(), ownerId)) {
                    Assets assets = new Assets();
                    assets.setRoomId(rooms.getRoomId());
                    assets.setOwnerId(ownerId);
                    assetsService.save(assets);
                }
            } catch (NumberFormatException e) {
                // 记录错误或处理异常
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); // 出现异常时手动回滚事务
                return Result.fail("所有者ID格式错误");
            }
        }

        // 如果一切正常，事务会自动提交
        return Result.success();
    }

    // 其他方法...
}




